package com.demo.job.dynamicjob;

import com.demo.job.dynamicjob.config.ScheduledTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Slf4j
@Component
public class CronTaskRegistrar {

    @Resource
    TaskScheduler taskScheduler;

    private final Map<String, ScheduledTask> scheduledTaskMap = new ConcurrentHashMap<>();

    public TaskScheduler getTaskScheduler() {
        return this.taskScheduler;
    }

    public void addCronTask(Runnable task, String cron, String cronKey) {
        addCronTask(new CronTask(task,cron), cronKey);
    }

    public void addCronTask(CronTask cronTask, String cronKey) {
        if (cronTask != null) {
            if (this.scheduledTaskMap.containsKey(cronKey)) {
                removeCronTask(cronKey);
            }
            //添加
            this.scheduledTaskMap.put(cronKey, scheduleCronTask(cronTask));
        }
    }

    /**
     * 移除定时任务
     * @param cronkey
     */
    public void removeCronTask(String cronkey) {
        ScheduledTask scheduledTask = this.scheduledTaskMap.remove(cronkey);
        if (scheduledTask != null) {
            scheduledTask.cancel();
        }
    }

    public ScheduledTask scheduleCronTask(CronTask cronTask) {
        ScheduledFuture<?> schedule = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        ScheduledTask scheduledTask = new ScheduledTask(schedule);
        return scheduledTask;
    }
}
